package com.authorization.demo.controller;

import com.authorization.demo.entity.MenuRole;
import com.authorization.demo.entity.RoleTable;
import com.authorization.demo.entity.UserRole;
import com.authorization.demo.entity.UserTable;
import com.authorization.demo.exception.TokenException;
import com.authorization.demo.request.FindRoleRequest;
import com.authorization.demo.request.FindUserRequest;
import com.authorization.demo.request.MenuDirectory;
import com.authorization.demo.service.MenuRoleService;
import com.authorization.demo.service.MenuService;
import com.authorization.demo.service.RoleTableService;
import com.authorization.demo.service.UserRoleService;
import com.authorization.demo.utils.TokenUtils;
import com.authorization.demo.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Remarks:
 * @ClassName: RoleTableController
 * @Author: Micora
 * @CreateTime: 2022/7/20
 */
@CrossOrigin //开放跨域访问
@RestController
@RequestMapping("/role")
@Api(tags = "角色管理")
public class RoleTableController {

    @Resource
    RoleTableService roleTableService;

    @Resource
    UserRoleService userRoleService;

    @Resource
    MenuRoleService menuRoleService;

    //创建用户
    @ApiOperation("创建角色")
    @PostMapping("/createRole")
    public R createRole(@RequestBody RoleTable roleTable, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "创建角色");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        if (roleTableService.FindOneIsExist(roleTable.getRoleName())) {
            return R.ok().setCode(403).setMessage("角色已存在");
        }
        roleTableService.save(roleTable);

        return R.ok();
    }

    //修改角色
    @ApiOperation("修改角色")
    @PostMapping("/alterRole")
    public R alterRole(@RequestBody RoleTable roleTable, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "修改角色");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        if (roleTableService.FindOneIsExist(roleTable.getRoleName())) {
            if (roleTableService.updateById(roleTable)) {
                return R.ok();
            }
        }
        return R.error().setMessage("修改出现问题");
    }

    //删除角色
    @ApiOperation("批量删除角色")
    @PostMapping("/deleteRole")
    public R deleteRole(@RequestParam String[] roleNames, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "删除角色");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        QueryWrapper<MenuRole> menuRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("ROLE_NAME", roleNames);
        menuRoleQueryWrapper.in("ROLE_NAME", roleNames);
        if (!userRoleService.list(userRoleQueryWrapper).isEmpty()) {
            return R.error().setMessage("要删除的角色中存在分配的用户，无法删除");
        }
        if (roleTableService.removeByIds(Arrays.asList(roleNames))) {
            userRoleService.remove(userRoleQueryWrapper);
            menuRoleService.remove(menuRoleQueryWrapper);
            return R.ok();
        }
        return R.error().setMessage("删除出现问题");
    }

    //根据角色名和状态进行查询
    @ApiOperation("带条件查询角色")
    @PostMapping("/findList")
    public R findList(@RequestBody FindRoleRequest findRoleRequest,@RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "查询角色");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        QueryWrapper<RoleTable> queryWrapper = new QueryWrapper<>();
        if (findRoleRequest.getRoleName() != null) {
            queryWrapper.like("ROLE_NAME", findRoleRequest.getRoleName());
        }
        if (findRoleRequest.getStatus() != 0) {
            queryWrapper.eq("STATUS", findRoleRequest.getStatus());
        }
        List<RoleTable> roleList = roleTableService.list(queryWrapper);

        return R.ok().data("roleList", roleList);
    }

    //根据角色名获取权限（菜单）列表
    @ApiOperation("根据角色名获取权限（菜单）列表")
    @PostMapping("/getPowerList")
    public R getPowerList(@RequestParam String roleName, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "分配权限");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        List<String> menuNameList = menuRoleService.GetMenuNameListByRoleName(roleName);


        return R.ok().data("menuNameList", menuNameList);
    }

    //根据权限（菜单）列表更改角色权限
    @ApiOperation("根据权限（菜单）列表更改角色权限")
    @PostMapping("/alterPower")
    public R alterPower(@RequestParam String roleName, @RequestParam String[] menuNames, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "分配权限");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        menuRoleService.deleteByRoleName(roleName);
        List<MenuRole> menuRoleList = new ArrayList<>();
        for (String menuName : menuNames) {
            MenuRole menuRole = new MenuRole(menuName, roleName);
            menuRoleList.add(menuRole);
        }
        menuRoleService.saveBatch(menuRoleList);
        return R.ok();
    }

   /* //嵌套获取某角色的菜单列表
    @ApiOperation("嵌套获取某角色的菜单列表")
    @GetMapping("/ViewRoleMenu")
    public R ViewRoleMenu(@RequestParam String roleName){
       *//* //嵌套的菜单目录实体类
            private String menuName;
            private List<com.authorization.demo.request.MenuDirectory> menuDirectories;
        }*//*
        List<String> menuNameList = menuRoleService.GetMenuNameListByRoleName(roleName);
        MenuDirectory menuDirectory;


        R r=null;
        return r;
    }*/


}
